/**
 * import api from '../../api' 只导入了default的内容
 * import * as api from '../../api' 导入了全部内容
 */

export function testMD5(str: string) {
    var MD5 = require("crypto-js/md5")
    return MD5(str).toString()
}

//parameter为JSON对象
export async function doPost(url, parameter) {
    //所需参数：api地址、接口私钥、时间戳、参数表
    //操作步骤：1.将参数表的key字典排序，然后以key + getValueByKey(key)的形式组成一个大的字符串content
    //2.用MD5对secretKey + timestamp + content进行签名，得到签名字符串sign
    //3.用参数表的字符串形式、签名、时间戳、来源构造Json，然后将Json转换成字符串，构造最终参数表，作为post请求参数发送给服务器

    //接口私钥
    var secretKey = "qfqwer23123WI="
    //完整访问地址（由接口地址和访问地址组成）
    var svcUrl = "http://intest.wangjushijie.com/svc/api" + url
    //时间戳
    var timestamp = new Date().getTime()
    //参数表Json字符串
    var parameterJsonString = JSON.stringify(parameter)
    //参数表keys
    var keys = []

    for (var key in parameter) {
        keys.push(key)
    }
    //将keys升序排序
    keys.sort()

    //参数表字符串（由key+value组成）
    var parameterString = ''
    for (var i = 0; i < keys.length; i++) {
        parameterString += keys[i]
        parameterString += parameter[keys[i]]
    }

    //MD5签名
    var MD5 = require("crypto-js/md5")
    var sign = MD5(secretKey + timestamp + parameterString).toString()

    //构造完整的参数表Json对象
    var fullParamsJson = {}
    fullParamsJson['data'] = parameterJsonString
    fullParamsJson['sign'] = sign
    fullParamsJson['timeStamp'] = timestamp
    fullParamsJson['source'] = 'android'
    console.log(JSON.stringify(svcUrl)+"*************************************");
    console.log(JSON.stringify(fullParamsJson)+"*************************************");
    var requestOptional = {
        method: "POST",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'paramJson=' + JSON.stringify(fullParamsJson)
    }


    var json = await fetch(svcUrl, requestOptional)
        .then((response) => { return response.json() })
        .then((json) => {
            return json
        })
        .catch((error) => {
            alert('网络请求失败，请重试' + error)
        })

    return json
}

//输入json格式的参数表，返回推荐商品信息列表
export async function getRecommendProductList(parameter) {
    var url = '/goods/getRecommendProductList'
    var json = await doPost(url, parameter)

    list1 = []
    list2 = []
    list3 = []
    //新品推荐
    var list1 = json.data.list1.map(
        (info) => {
            return {
                'imageUrl': info.list_image,
                'title': info.full_name,
                'price': info.member_price,
                'id': info.id,
                'description':info.detail_name,
            }
        }
    )
    //新人推荐
    var list2 = json.data.list2.map(
        (info) => {
            return {
                'imageUrl': info.list_image,
                'title': info.full_name,
                'buyNum': info.sales_volume,
                'earn': info.profit,
                'price': info.member_price,
                'id': info.id,
                'description':info.detail_name,
            }
        }
    )
    //热销爆款
    var list3 = json.data.list3.map(
        (info) => {
            return {
                'imageUrl': info.list_image,
                'title': info.full_name,
                'buyNum': info.sales_volume,
                'earn': info.profit,
                'price': info.member_price,
                'id': info.id,
                'description':info.detail_name,
            }
        }
    )

    var list = [list1, list2, list3]
    return list
}

//输入json格式的参数表，返回图片链接数组
export async function getAdvertisingList(parameter) {
    var url = '/goods/getAdvertisingList'
    var json = await doPost(url, parameter)

    var dataList = json.data.map(
        (info) => {
            return {
                'imageUrl': info.imageUrl,
                'url': info.url,
                'id': info.id,
                
            }
        }
    )

    return dataList
}
//根据一级类目id，获取二级类目
export async function getSecondCategoryList(parameter) {
    var url = '/search/secondCate'
    var json = await doPost(url, parameter)
    var dataList = json.data.map(
        (info) => {
            return {
                'id': info.id,
                'icon': info.icon,
                'name': info.cateName,
            }
        }
    )
    return dataList
}
//输入json格式的参数表，返回团购商品信息列表
export async function getGroupPurchaseList(parameter) {
    var url = '/activity/getGroupShoppingList'
    var json = await doPost(url , parameter)
    var dataList = json.data.map(
        (info) => {
            return {
                'imageUrl':info.imageUrl,
                'full_title':info.full_title,
                'price':info.price,
                'success_count':info.success_count,
                'imageMan0':info.imageMan0,
            }
        }
    )
    return dataList
}